/*
 * Created on 13.02.2009
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.higginsexamples.mailboxserver;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.pf.file.FileUtil;
import org.pf.text.StringUtil;

public class MailboxRetrievalServlet extends HttpServlet
{
	protected static final StringUtil SU = StringUtil.current() ;
	private static final String[] SAMPLE_NAMES = { "fred.flintstone@stoneage.com", "mickey.mouse@disney.com", "tom@tomandjerry.org" } ;
	
	@Override
	protected void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException
	{
		PrintWriter writer ;
		
		response.setContentType( "text/xml" ) ;
		writer = response.getWriter() ;
		
		writer.println( "<?xml version='1.0' encoding='ISO-8859-1'?>" );
		writer.println( "<rcpmail>" ) ;
		writer.println( "<name>Mailboxes</name>" ) ;
		writer.println( "<children>" ) ;
		this.includeMailboxes( request, writer ) ;
		writer.println( "</children>" ) ;
		writer.println( "</rcpmail>" ) ;
	}
	
	protected void includeMailboxes( HttpServletRequest request, PrintWriter writer )  
	{
		String attrValue ;
		String[] mailboxNames ;
		
//		mailboxNames = SAMPLE_NAMES ;
		attrValue = (String) request.getAttribute( CommonConstants.MAILBOXES ) ;
		mailboxNames = SU.trimmedParts( attrValue, "," );
		
		for (String name : mailboxNames )
		{
			this.includeMailbox( writer, name ) ;
		}
	}

	protected void includeMailbox( PrintWriter writer, String mailboxName )  
	{
		String data ;
		
		try
		{
			data = this.readDataFile( mailboxName ) ;
			writer.println( data );
		}
		catch ( IOException ex )
		{
			writer.println( "<exception>" ) ;
			ex.printStackTrace( writer ) ;
			writer.println( "</exception>" ) ;
		}
	}
	
	protected String readDataFile( String mailboxName ) throws IOException 
	{
		String data ;
		URL url ;
		InputStream inStream ;
		
		url = Activator.BUNDLE.getEntry( "/data/" + mailboxName + ".xml" ) ;
		inStream = url.openStream() ;
		data = FileUtil.current().readTextFrom( inStream ) ;
		return data ;
	} 
	
} 
